﻿// ***********************************************************************
// Assembly         : ELS
// Author           : linhvn
// Created          : 10-20-2012
//
// Last Modified By : linhvn
// Last Modified On : 10-22-2012
// ***********************************************************************
// <copyright file="UserController.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Win32;
using System.Windows.Forms;

namespace ELS.User
{
    /// <summary>
    /// Class UserController
    /// </summary>
    public class UserController
    {
        /// <summary>
        /// The user data access
        /// </summary>
        UserDataAccess userDataAccess = new UserDataAccess();

        /// <summary>
        /// Logs the in.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns>System.Int32.</returns>
        public int LogIn(string username, string password)
        { 
            
            int result = -1;
            DataTable dtTable = new DataTable();            

            // get data table return from data access
            dtTable = userDataAccess.GetUserInfoByUsername(username);

            // check data table is null or not null
            bool isDataNull = (dtTable == null);
            
            if (isDataNull)
            {
                return result;
            }
            else
            {
                bool isUsernameExist = dtTable.Rows.Count > 0;

                if (isUsernameExist)
                {
                    string passwordOpposite = dtTable.Rows[0]["PASSWORD"].ToString();

                    bool isMatchPassword = (password == passwordOpposite);

                    if (isMatchPassword)
                        result = 2;
                    else
                        result = 1;
                }
                else
                    result = 0;
    
            }            
            return result;
        }

        /// <summary>
        /// Checks the exist username.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        internal bool CheckExistUsername(string username)
        {
            DataTable dtUser = new DataTable();
            dtUser = userDataAccess.CheckExistUserByUsername(username);
            bool isExistUsername = false;
            isExistUsername = dtUser.Rows.Count > 0;
            return isExistUsername;
        }

        /// <summary>
        /// Adds the new user.
        /// </summary>
        /// <param name="newUser">The new user.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        internal bool AddNewUser(User newUser)
        {
            bool isAddNewUserSuccess = false;

            isAddNewUserSuccess = userDataAccess.InsertUser(newUser) > 0;
            return isAddNewUserSuccess;
        }       

        /// <summary>
        /// Saves to registry.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        internal void SaveToRegistry(string username, string password)
        {
            bool isValidPassword = password.Length > 0;
            string encryptPassword = "";
            if (isValidPassword)
            {
                encryptPassword = UserCommon.Encrypt(password);
            }            
            RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(UserCommon.keyNameRegistry);
            registryKey.SetValue("Username", username);
            registryKey.SetValue("Password", encryptPassword);
            registryKey.Close();
        }

        /// <summary>
        /// Gets the remember user.
        /// </summary>
        /// <returns>System.String[][].</returns>
        internal string[] GetRememberUser()
        {
            string[] userInfo = { "", "" };
            try
            {
                RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(UserCommon.keyNameRegistry);
                object registryUsernameObject = registryKey.GetValue("Username");
                if (null != registryUsernameObject)
                {
                    userInfo[0] = registryUsernameObject.ToString();
                }

                object registryPasswordObject = registryKey.GetValue("Password");
                if (null != registryPasswordObject)
                {
                    string decryptPassword = UserCommon.Decrypt(registryPasswordObject.ToString());
                    userInfo[1] = decryptPassword;
                }

                return userInfo;
            }
            catch (Exception ex)
            {
                return userInfo;
            }            
        }

        /// <summary>
        /// Gets all Group.
        /// </summary>
        /// <param name="cmbGroups">The CMB Groups.</param>
        internal void GetAllGroup(ComboBox cmbGroups )
        {
            DataTable dtGroup = new DataTable();
            dtGroup = userDataAccess.SelectAllGroup();
            cmbGroups.DataSource = dtGroup;
            cmbGroups.DisplayMember = "NAME";
            cmbGroups.ValueMember = "ID";
        }

        /// <summary>
        /// Gets the fullname by username.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns>System.String.</returns>
        internal string GetFullnameByUsername(string username)
        {
            string fullname = String.Empty;
            fullname = userDataAccess.SelectFullnameByUsername(username);
            return fullname;
        }

        /// <summary>
        /// Gets the total number of user in system
        /// </summary>
        internal int CountAllUsers()
        {
            return userDataAccess.CountAllUsers();
        }

        /// <summary>
        /// Gets the total number of user in system
        /// </summary>
        internal int CountAllUsersByKeyword(string keyword)
        {
            return userDataAccess.CountAllUsersByKeyword(keyword);
        }

        /// <summary>
        /// Gets the total number of user in system
        /// </summary>
        internal DataTable GetAllUsersPaging(int mintPageSize, int intSkip)
        {
            DataTable dtAllUserPaging = new DataTable();
            dtAllUserPaging = userDataAccess.GetAllUsersPaging(mintPageSize, intSkip);
            return dtAllUserPaging;
        }

        /// <summary>
        /// Gets the total number of user in system by searching keyword
        /// </summary>
        internal DataTable GetAllUsersByKeywordPaging(string keyword, int mintPageSize, int intSkip)
        {
            DataTable dtAllUsersPaging = new DataTable();
            dtAllUsersPaging = userDataAccess.GetAllUsersByKeywordPaging(keyword, mintPageSize, intSkip);
            return dtAllUsersPaging;
        }

        /// <summary>
        /// Gets the userby username.
        /// </summary>
        /// <param name="selectUsername">The select username.</param>
        /// <returns>Users.</returns>
        internal User GetUserInfoByUsername(string selectUsername)
        {
            User selectUser = new User();
            try
            {
                DataTable dtUser = new DataTable();
                dtUser = userDataAccess.GetUserInfoByUsername(selectUsername);
                if (dtUser.Rows.Count > 0)
                {
                    selectUser.UserId = dtUser.Rows[0]["USER_USERID"].ToString();
                    selectUser.Username = dtUser.Rows[0]["USERNAME"].ToString();
                    selectUser.Password = dtUser.Rows[0]["PASSWORD"].ToString();
                    selectUser.Fullname = dtUser.Rows[0]["FULLNAME"].ToString();
                    selectUser.Email = dtUser.Rows[0]["EMAIL"].ToString();
                    selectUser.Address = dtUser.Rows[0]["ADDRESS"].ToString();
                    selectUser.Phone = dtUser.Rows[0]["PHONE"].ToString();
                    selectUser.Organization = dtUser.Rows[0]["ORGANIZATION"].ToString();
                    //selectUser.Group = dtUser.Rows[0]["GROUP_DESCRIPTION"].ToString();

                    return selectUser;
                }
                else
                    return selectUser;
            }
            catch (Exception e)
            {
                return selectUser;
            }
        }

        /// <summary>
        /// Updates the user.
        /// </summary>
        /// <param name="editUser">The edit user.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        internal bool UpdateUser(User editUser)
        {
            bool isUpdateUserSuccess = false;
            isUpdateUserSuccess = userDataAccess.UpdateUser(editUser) > 0;
            return isUpdateUserSuccess;
        }

        /// <summary>
        /// Deletes the select user.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        internal bool DeleteSelectedUser(List<string> list)
        {
            bool isDeleteUserSuccess = false;
            isDeleteUserSuccess = userDataAccess.DeleteUser(list) > 0;
            return isDeleteUserSuccess;
        }

        internal List<int> CheckGroupByUsername(string username)
        {
            List<int> listRoles = new List<int>();
            DataTable dtListRoles = userDataAccess.GetGroupIdByUsername(username);
            for (int i = 0; i < dtListRoles.Rows.Count; i++)
            {
                int k = int.Parse(dtListRoles.Rows[i]["GROUP_ID"].ToString());
                listRoles.Add(k);
            }
            return listRoles; 
        }
    }
 }

